﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bluefly
{

    public class DataBuffer
    {
        private List<IDatasource> dataSources;
        private List<BufferData> data;
        private int bufferSize;
        private int position;
        private bool full;
        private bool empty;
        private int sampleRate;
        private int sampleRateCounter;


        public DataBuffer(List<IDatasource> dataSources, int bufferSize, int sampleRate)
        {
            this.dataSources = dataSources;
            this.bufferSize = bufferSize;
            this.sampleRate = sampleRate;
            initBuffer();
        }

        public void initBuffer()
        {
            data = new List<BufferData>();
            for (int i = 0; i < dataSources.Count(); i++)
            {
                data.Add(new BufferData(bufferSize));

            }
            empty = true;
            position = 0;
            sampleRateCounter = sampleRate;  //we are going to take the first data point we get.
        }


        public void addData()
        {
            if (sampleRateCounter < sampleRate)
            {
                sampleRateCounter++;
                return;
            }

            sampleRateCounter = 1;
            position++;
            if (position >= bufferSize)
            {
                position = 0;
                full = true;
            }

            for (int i = 0; i < dataSources.Count(); i++)
            {
                if (empty)
                {
                    for (int pos = 0; pos < bufferSize; pos++)
                    {
                        data[i].getData()[pos] = dataSources[i].Value;
                    }

                }
                data[i].getData()[position] = dataSources[i].Value;
                data[i].setPosition(position);

            }
            if (empty)
            {
                empty = false;
            }

        }

        public BufferData getData(IDatasource dataSource)
        {

            if (dataSources.Contains(dataSource))
            {
                return data[dataSources.IndexOf(dataSource)];

            }
            return null;
        }

        public int getBufferSize()
        {
            return bufferSize;
        }
    }

}
